package cn.tedu.clyback.user.controller;


import cn.tedu.clyback.base.response.JsonResult;
import cn.tedu.clyback.base.response.StatusCode;
import cn.tedu.clyback.user.pojo.dto.UserLoginParam;
import cn.tedu.clyback.user.pojo.dto.UserQuery;
import cn.tedu.clyback.user.pojo.dto.UserSaveParam;
import cn.tedu.clyback.user.pojo.vo.PermissionVO;
import cn.tedu.clyback.user.pojo.vo.UserVO;
import cn.tedu.clyback.user.service.UserService;
import com.google.code.kaptcha.Producer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/v1/user")
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    private Producer captchaProducer;
    @Autowired
    private HttpServletRequest request;

    @PostMapping("login")
    public JsonResult login(UserLoginParam userLoginParam) {

        log.debug("用户登录，userLoginParam={}", userLoginParam);

        // 获取用户输入的验证码和 Session 中存储的验证码
        String captcha = userLoginParam.getCaptcha();
        String storedCode=(String)request.getSession().getAttribute("captcha");
        log.debug("storedCode={}", storedCode);
        // 比对验证码
        if (captcha != null && captcha.equalsIgnoreCase(storedCode)) {
            request.getSession().removeAttribute("captcha"); // 验证通过后删除验证码，防止重复使用
            // 执行用户登录逻辑
            UserVO userVO = userService.login(userLoginParam);
            return JsonResult.ok(userVO); // 登录成功返回用户信息
        } else {
            // 验证码错误的处理逻辑
            return new JsonResult(StatusCode.CHECKCODE_ERROR);
        }
    }
//获取用户权限
  /*  @GetMapping("/getuserpermissions/{userId}")
    public  JsonResult getPermissions(@PathVariable Integer userId){
        log.debug("获取用户权限ID，userId={}",userId);
        List<PermissionVO> list=userService.getPermissions(userId);
        return JsonResult.ok(list);
    }*/
    @GetMapping("/getuserpermissions/{userId}")
    public  JsonResult getPermissions(@PathVariable Integer userId){
        log.debug("获取用户权限ID，userId={}",userId);
        HashSet<PermissionVO> set=userService.getPermissions(userId);
        return JsonResult.ok(set);
    }

//校验
    @GetMapping("/captcha/generate")
    public void getCaptcha(HttpServletResponse response) throws IOException {
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        // 生成验证码文本
        String capText = captchaProducer.createText();
        log.debug("Generated Captcha: {}", capText);
        // 将验证码文本存储在 session 中，便于后续验证
        request.getSession().setAttribute("captcha", capText);
        String aaa=(String)request.getSession().getAttribute("captcha");
        log.debug("aaa={}", aaa);
        // 生成验证码图像
        BufferedImage bi = captchaProducer.createImage(capText);
        // 将图像写入响应输出流
        ImageIO.write(bi, "jpg", response.getOutputStream());
    }
    @PostMapping("save")
    public JsonResult saveUser(UserSaveParam userSaveParam) {
        log.debug("保存用户,userSaveParam={}", userSaveParam);
        userService.saveUser(userSaveParam);
        return JsonResult.ok();
    }


    //查询用户
    @GetMapping("select")
    public JsonResult selectUser(UserQuery userQuery) {
        log.debug("查询用户,userQuery={}", userQuery);
        List<UserVO> list = userService.selectUser(userQuery);
        log.debug("查询结果，list={}", list);
        return JsonResult.ok(list);

    }
    @PostMapping("/update/password/{userId}")
    public JsonResult resetPassword(@PathVariable Long userId){
        log.debug("重置密码，userId={}",userId);
        userService.resetPassword(userId);
        return JsonResult.ok();
    }
    @PostMapping("update/status/{userId}/{status}")
    public JsonResult updateStatus(@PathVariable Long userId,@PathVariable String status){
        log.debug("修改用户状态，userId={},status={}",userId,status);
        userService.updateStatus(userId,status);
        return JsonResult.ok();
    }

    @PostMapping("/delete/{userId}")
    public JsonResult deleteUser(@PathVariable Long userId){
        log.debug("删除用户，userId={}",userId);
        userService.deleteUser(userId);
        return JsonResult.ok();
    }
}